package com.shanling.shanlingcontroller.utils

import android.content.Context
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import com.shanling.shanlingcontroller.CustomApplication
import com.shanling.shanlingcontroller.bean.BluetoothState
import com.shanling.shanlingcontroller.bean.Constants
import com.shanling.shanlingcontroller.bean.EventCenter
import com.shanling.shanlingcontroller.music.event.PlaylistEvent
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * Created by ch1 on 2019/11/7.
 */
object ScanFileHelper {

    /**
     * 扫描文件夹
     *
     * @param ctx
     * @param filePath
     */
    fun scanFileAsync(ctx: Context, filePath: String) {
        val scanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        scanIntent.data = Uri.fromFile(File(filePath))
        ctx.sendBroadcast(scanIntent)
        scanFileAsync(ctx)
    }

    /**
     * 扫描文件夹
     *
     * @param ctx
     * @param filePath
     */
    fun scanFileAsync(ctx: Context) {
        //MediaScannerConnectionClient 是媒体扫描服务在MediaScannerConnection类中返回新添加文件的 uri  和 path
        val scanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        scanIntent.data = Uri.fromFile(File(FileUtils.getMusicDir()))
        ctx.sendBroadcast(scanIntent)

        MediaScannerConnection.scanFile(CustomApplication.getInstance(), arrayOf(FileUtils.getMusicDir()), null,
                object : MediaScannerConnection.MediaScannerConnectionClient {
                    override fun onMediaScannerConnected() {
                        // MediaScanner service 创建后回调
                    }

                    override fun onScanCompleted(path: String?, uri: Uri?) {
                        // 当MediaScanner完成文件扫描后回调
                       EventBus.getDefault().post(EventCenter(Constants.PLAYLISTEVENT,PlaylistEvent(Constants.PLAYLIST_LOCAL_ID)))
                    }
                })
    }

}